<template>
  <div class="height_width-full">
    <div class="breadcrumb">
      <div class="breadcrumb-icon-box">
        <i class="el-icon-location-outline"></i>
      </div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path : '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>个人信息</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-divider></el-divider>
    <el-row>
      <el-col :span="24">
        <el-card class="box-card">
          <el-row>
            <el-col :span="12">
              <div>
                <div class="user-info-box " :style="{backgroundImage: 'url(' + src + ')'}">
                  <table>
                    <tr>
                      <td>账号：</td>
                      <td>{{ userInfo.loginName }}</td>
                    </tr>
                    <tr>
                      <td>用户名：</td>
                      <td>{{ userInfo.username }}</td>
                    </tr>
                    <tr>
                      <td>昵称：</td>
                      <td>{{ userInfo.nickname }}</td>
                    </tr>
                    <tr>
                      <td>性别：</td>
                      <td>{{ userInfo.gender == 1 ? "男" : "女" }}</td>
                    </tr>
                    <tr>
                      <td>手机号：</td>
                      <td>{{ userInfo.phone }}</td>
                    </tr>
                    <tr>
                      <td>生日：</td>
                      <td>{{ new Date(userInfo.birthday).format("yyyy-MM-dd") }}</td>
                    </tr>
                    <tr>
                      <td>职位：</td>
                      <td>{{ userInfo.post }}</td>
                    </tr>
                  </table>
                </div>
                <div class="btn-box">
                  <el-button type="success" icon="el-icon-lock" @click="passwordDrawer = true">修改密码</el-button>
                  <el-button type="primary" icon="el-icon-postcard" @click="userInfoDrawer = true">修改个人资料</el-button>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div>
                <el-image :src="this.$api.SERVER_URL+userInfo.img">
                  <div slot="placeholder" class="image-slot">
                    加载中<span class="dot">...</span>
                  </div>
                </el-image>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <el-drawer
      title="修改密码"
      :visible.sync="passwordDrawer"
      :with-header="true"
      direction="ltr">
      <template>
        <el-row>
          <el-col>
            <div class="password-box">
              <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="原始密码" prop="oldPassword">
                  <el-input v-model="userForm.oldPassword"
                            placeholder="请输入原始密码"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input v-model="userForm.newPassword"
                            placeholder="请输入新密码"></el-input>
                </el-form-item>
                <el-form-item label="重复密码" prop="rePassword">
                  <el-input v-model="userForm.rePassword"
                            placeholder="请输入重复密码"></el-input>
                </el-form-item>
                <el-form-item prop="name">
                  <template>
                    <el-button type="success" @click="savePassword('userForm')">提交</el-button>
                    <el-button type="info" @click="resetForm('userForm')">重置</el-button>
                  </template>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
        </el-row>
      </template>
    </el-drawer>
    <el-drawer
      title="修改个人资料"
      :visible.sync="userInfoDrawer"
      :with-header="true"
      size="40%"
      direction="rtl">
      <template>
        <el-row>
          <el-col>
            <div class="update-user-info-box">
              <el-form :model="userInfoForm" :rules="userInfoRules" ref="userInfoForm" label-width="100px"
                       class="demo-ruleForm">
                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="userInfoForm.nickname" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item label="生日" prop="birthday">
                  <el-date-picker
                    v-model="userInfoForm.birthday"
                    type="date"
                    placeholder="请选择出生日期"
                    align="right"
                    :picker-options="pickerOptions">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                  <el-radio v-model="userInfoForm.gender" :label="1">男</el-radio>
                  <el-radio v-model="userInfoForm.gender" :label="2">女</el-radio>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="userInfoForm.phone" placeholder="请输入手机号码"></el-input>
                </el-form-item>
                <el-form-item prop="name">
                  <template>
                    <el-button type="success" :disabled="disabled" @click="submitForm('userInfoForm')">提交</el-button>
                    <el-button type="info" @click="resetForm('userInfoForm')">重置</el-button>
                  </template>
                </el-form-item>
              </el-form>
              <div class="upload-img-box">
                <el-upload
                  :file-list="fileList"
                  :action="this.$api.API_FILE_UPLOAD"
                  :headers="fileUploadHeaders"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :before-upload="handBeforeUpload"
                  :on-success="handleAvatarSuccess"
                  :on-remove="handleRemove">
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="userInfoForm.img" alt="">
                </el-dialog>
              </div>
            </div>
          </el-col>
        </el-row>
      </template>
    </el-drawer>
  </div>
</template>

<script>
export default {
  name: "AssetUser",
  data() {
    let checkTwoPassSame = (rule, value, callback) => {
      if (value.trim() != this.userForm.newPassword.trim()) {
        callback(new Error('两次密码不一致'));
      }
      callback();
    }

    return {
      disabled: false,
      dialogVisible: false,
      fileUploadHeaders: {
        Authorization: this.$store.getters.getToken ? this.$store.getters.getToken : this.Storage.Local.get("token")
      },
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      userInfoRules: {
        nickname: [
          {required: true, message: '请输入用户昵称', trigger: 'blur'},
          {min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入电话号码', trigger: 'blur'},
          {required: true, pattern: /^1[3-9][\d]{9}$/, message: '请输入正确的电话号码', trigger: 'blur'}
        ],
        gender: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
        birthday: [
          {required: true, message: '请选择出生日期', trigger: 'blur'}
        ],
      },
      userInfoForm: {
        id: this.$store.getters.getUser.id,
        nickname: this.$store.getters.getUser.nickname,
        gender: this.$store.getters.getUser.gender,
        phone: this.$store.getters.getUser.phone,
        birthday: this.$store.getters.getUser.birthday,
        img: this.$store.getters.getUser.img
      },
      rules: {
        oldPassword: [
          {required: true, message: "请输入原始密码", trigger: 'blur'},
          {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'}
        ],
        newPassword: [
          {required: true, message: "请输入新密码", trigger: 'blur'},
          {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'}
        ],
        rePassword: [
          {required: true, message: "请输入重复密码", trigger: 'blur'},
          {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'},
          {validator: checkTwoPassSame, trigger: 'blur'}
        ]
      },
      userForm: {
        id: this.$store.getters.getUser.id,
        loginName: this.$store.getters.getUser.loginName,
        oldPassword: "",
        newPassword: "",
        rePassword: ""
      },
      imgUploadDrawer: false,
      passwordDrawer: false,
      userInfoDrawer: false,
      src: require('@/assets/images/bg.png'),
      fileList: []
    };
  },
  computed: {
    userInfo() {
      return this.$store.getters.getUser;
    }
  },
  created() {
    this.fileList.push({
      name: this.$store.getters.getUser.nickname + "的头像",
      url: this.$api.SERVER_URL + this.userInfoForm.img
    })
  },
  methods: {
    toDisabled() {
      this.disabled = true;
      setTimeout(() => {
        this.disabled = false;
      }, 500)
    },
    submitForm(formName) {
      this.toDisabled();
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.fileList.length) {
            this.$notify.warning("请上传一个头像");
            return;
          }
          this.$put(this.$api.API_USER_ADD, this.userInfoForm).then(res => {
            console.log(res);
            if (res.data.code == 200) {
              this.$notify.success("保存成功");
              let user = this.$store.getters.getUser;
              user.nickname = this.userInfoForm.nickname;
              user.gender = this.userInfoForm.gender;
              user.phone = this.userInfoForm.phone;
              user.birthday = this.userInfoForm.birthday;
              user.img = this.userInfoForm.img;
              this.$store.commit("setUser", user);
              this.userInfoDrawer = false;
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handBeforeUpload(file) {
      console.log(file);
      console.log(this.fileList.length);
      if (this.fileList.length > 0) {
        this.$notify.warning("最多上传一个头像");
        return false;
      }
    },
    handleAvatarSuccess(response, file, fileList) {
      console.log(fileList)
      this.fileList = fileList;
      console.log(this.fileList)
      if (response.code == 200) {
        this.$notify.success(response.message);
        this.userInfoForm.img = response.data.url;
      } else {
        this.$notify.error("文件太大，最大能上传2MB")
        fileList.splice(0, fileList.length);
      }
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.userInfoForm.img = file.url;
      this.dialogVisible = true;
    },
    savePassword(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$post(this.$api.API_USER_UPDATE_PASS, this.userForm).then(res => {
            console.log(res);
            if (res.data.code == 200) {
              this.$message.success("修改成功，请重新登录");
              this.$store.commit('setUser', null);
              this.$store.commit('setToken', null);
              this.$router.push("/login");
            }
          })
        } else {
          this.$message.info("请填写完整表单信息");
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>
.user-info-box {
  background-repeat: no-repeat;
  background-size: 100%;
  padding-left: 3em;
}

.password-box {
  padding-right: 20px;
}

.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 100%;
}

tr {
  height: 50px;
}

tr > td:first-child {
  text-align: right;
}

tr > td:last-child {
  padding-left: 30px;
}

.btn-box {
  margin-top: 30px;
  padding-left: 30px;
}

.update-user-info-box {
  padding: 0 50px 0 0;
}

.upload-img-box {
  margin-left: 50px
}
</style>
